<template>
  <el-drawer v-model="open" title="设备选择" size="60%">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择" @change="changeQueryType" filterable clearable style="width:120px">
          <el-option
            v-for="dict in queryTypeOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="型号" prop="modelId">
        <el-select v-model="queryParams.modelId" placeholder="请选择" filterable clearable style="width:120px">
          <el-option
            v-for="dict in modelOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备" prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="请输入设备位置/编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="props.mode == 'checkbox'"
          type="primary"
          plain
          icon="Selection"
          @click="handleSelect()"
        >确定选择</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Selection"
          @click="handleClear"
        >清除选择</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Selection"
          @click="handleClose"
        >关闭</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" v-if="props.mode == 'checkbox'"/>
      <el-table-column label="场馆" align="center" prop="deptId" />
      <el-table-column label="设备类型" align="center" prop="typeName" />
      <el-table-column label="型号" align="center" prop="modelName" />
      <el-table-column label="设备编码" align="center" prop="code" />
      <el-table-column label="设备位置" align="center" prop="position" />
      <el-table-column label="图例" align="center" prop="imgs" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imgs" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="运行状态" align="center" prop="runStatus">
        <template #default="scope">
          <dict-tag :options="run_status" :value="scope.row.runStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  v-if="props.mode == 'radio'">
        <template #default="scope">
          <el-button link type="primary" icon="Selection" @click="handleSelect(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </el-drawer>
</template>

<script setup name="DeviceSelection">
import { selectDevice } from "@/api/base/device";
import { selectModel } from "@/api/base/model";
import { listType } from "@/api/base/type";

const { proxy } = getCurrentInstance();
const { device_status, run_status } = proxy.useDict('device_status', 'run_status');
const emit = defineEmits(['selected', 'cancel', 'clear']);

const deviceList = ref([]);
const typeOptions = ref([]);
const modelOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const names = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const props = defineProps({
  // 选中数据
  ids: [String, Array],
  type: [String, Array],
  limit: {
    type: Number,
    required: true,
    default: 0
  },
  // 模式
  mode: {
    type: String,
    required: true,
    default: 'none'
  }
});

const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 't.id',
    isAsc: 'desc',
    deptId: null,
    sysId: null,
    typeId: null,
    modelId: null,
    code: null,
    position: null,
    runStatus: null,
    useStatus: null,
    scrapDate: null,
    typeCode: null,
    pfCode: null
});

watch(() => props.mode, val => {
  open.value = (val != 'none');
  ids.value = [];
  names.value = [];
},{ deep: true, immediate: true });

watch(() => props.type, val => {
  queryParams.value.typeCode = val;
  getList();
},{ deep: true, immediate: true });


const queryTypeOptions = computed(() => {
    if(typeOptions.value == null || typeOptions.value.length == 0){
        return [];
    }
    let list = [];
    let typeCodes = [];
    if(!props.type){
        typeCodes =[];
    }else if(Array.isArray(props.type)){
        typeCodes = props.type;
    }else{
        typeCodes = props.type.split(',');
    }
    for(let i=0;i<typeOptions.value.length;i++){
        let type = typeOptions.value[i];
        if(type.isLeaf == 'N'){
            continue;
        }else if(typeCodes.length > 0 && !typeCodes.includes(type.code)){
            continue;
        }else{
            list.push(type);
        }
    }
    return list;
})

/** 查询设备信息列表 */
function getList() {
  loading.value = true;
  selectDevice(queryParams.value).then(response => {
    deviceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 更换设备类型 */
function changeQueryType(){
  selectModel({typeId: queryParams.value.typeId}).then(response=>{
    modelOptions.value = response.rows;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  names.value = selection.map(item => item.position);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function handleSelect(row) {
    if(row){
        emit('selected', {id:row.id, name:row.position});
    }else if(ids.value.length == 0){
          proxy.$modal.msgError("请至少选择一条数据");
          return;
    }else if(props.limit > 0 && ids.value.length > props.limit){
          proxy.$modal.msgError("最多只能选择"+props.limit+"条数据");
          return;
    }else{
        emit('selected', {id: ids.value.join(','), name: names.value.join(',')});
    }
}

function handleClear(){
  emit('clear')
}
function handleClose(){
  open.value = false;
  emit('close')
}

getList();
listType().then(response => {
  typeOptions.value = response.data;
});
</script>
